package com.ruoyi.crop.controller;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.crop.api.domain.ClassAround;
import com.ruoyi.crop.api.domain.PlanClasses;
import com.ruoyi.crop.api.domain.TeamsGroups;
import com.ruoyi.crop.service.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("plan")
public class PlanClassController extends BaseController {
    @Autowired
    PlanClassesService srcPlanClassesService;
    @Autowired
    ClassAroundService srcClassAroundService;
    @Autowired
    TeamsGroupsService teamsGroupsService;
    @Autowired
    AroundTeamService aroundTeamService;
    @Autowired
    PlanAroundService planAroundService;
    @RequestMapping("exportToExcel")
    @Transactional
    //异常时能够回滚事务
    public void exportToExcel(Map<String, Object> dataMap) throws IOException {
        Workbook workbook = new XSSFWorkbook();//使用 XSSFWorkbook 创建一个新的 Excel 工作簿
        Sheet sheet = workbook.createSheet("Report");//工作簿中创建名为 "Report" 的工作表
        dataMap.put("PlanLists", srcPlanClassesService.list());//往map里填充数据
// 填充数据
        fillSheet(sheet, dataMap);


         // 生成动态的文件路径
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String fileName = "Report_" + timestamp + ".xlsx";
        String filePath = "/E:/每日练习下载word文档/" + fileName; // 修改为实际的文件存储路径

        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);//使用 FileOutputStream 将工作簿写入到指定的文件路径 filePath 中
            System.out.println("Excel 导出成功：" + filePath);
        } catch (IOException e) {
            System.err.println("导出 Excel 文件时出现异常：" + e.getMessage());
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                System.err.println("关闭 Workbook 时出现异常：" + e.getMessage());
            }
        }

    }

    private void fillSheet(Sheet sheet, Map<String, Object> dataMap) {
        //从 dataMap 中获取名为 "PlanLists" 的数据列表，这里假设是 List<PlanClasses> 类型
        List<PlanClasses> planClassesList = (List<PlanClasses>) dataMap.get("PlanLists");
        System.err.println(planClassesList);
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        //对每个对象创建一行 Row，并为每列创建单元格 Cell，并将对应的属性值填充进去
        headerRow.createCell(0).setCellValue("planId");
        headerRow.createCell(1).setCellValue("planCode");
        headerRow.createCell(2).setCellValue("planName");
        headerRow.createCell(3).setCellValue("typeId");
        headerRow.createCell(4).setCellValue("beginTime");
        headerRow.createCell(5).setCellValue("endTime");
        headerRow.createCell(6).setCellValue("aroundId");
        headerRow.createCell(7).setCellValue("wayId");
        headerRow.createCell(8).setCellValue("documentStatus");
        headerRow.createCell(9).setCellValue("remark");

        // 填充数据
        int rowIndex = 1; // 从第二行开始填充数据
       // /使用 for 循环遍历 planClassesList 中的每个 PlanClasses 对象。
        for (PlanClasses planClasses : planClassesList) {
            Row row = sheet.createRow(rowIndex);
            //setCellValue() 方法用于设置单元格的值
            row.createCell(0).setCellValue(planClasses.getPlanId());
            row.createCell(1).setCellValue(planClasses.getPlanCode());
            row.createCell(2).setCellValue(planClasses.getPlanName());
            row.createCell(3).setCellValue(planClasses.getTypeId());
            row.createCell(4).setCellValue(planClasses.getBeginTime()); // 假设这些属性有相应的获取方法
            row.createCell(5).setCellValue(planClasses.getEndTime());
            row.createCell(6).setCellValue(planClasses.getAroundId());
            row.createCell(7).setCellValue(planClasses.getWayId());
            row.createCell(8).setCellValue(planClasses.getDocumentStatus());
            row.createCell(9).setCellValue(planClasses.getRemark());
            rowIndex++;
        }
    }


    @GetMapping("selectMaterialCode")
    public AjaxResult selectMaterialCode(){
        String s = IdUtil.getSnowflake().nextIdStr();
        return success(s);
    }

    @GetMapping("/list")
    public TableDataInfo list(PlanClasses srcPlanClasses)
    {
        startPage();
        List<PlanClasses> list = srcPlanClassesService.lists(srcPlanClasses);
        return getDataTable(list);
    }



    //获取轮班类型
    @RequestMapping("AroundLists")
    public AjaxResult AroundLists() throws ParseException {
        List<ClassAround> list=srcClassAroundService.list();
        return success(list);
    }

//    //完成按钮
//    @RequestMapping("successBan")
//    public AjaxResult successBan(@RequestBody PlanClasses srcPlanClasses) {
//        boolean foundNonEmptyTeam = true; // 初始假设至少存在一个非空班组
//
//        LambdaQueryWrapper<ClassAround> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(ClassAround::getAroundId, srcPlanClasses.getAroundId());
//
//        List<ClassAround> classArounds = srcClassAroundService.list(lambdaQueryWrapper);
//
//        for (ClassAround classAround : classArounds) {
//            LambdaQueryWrapper<AroundTeam> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(AroundTeam::getAroundId, classAround.getId());
//            List<AroundTeam> teamList = aroundTeamService.list(wrapper);
//
//            // 判断是否找到符合条件的 AroundTeam
//            for (AroundTeam aroundTeam : teamList) {
//                if (aroundTeam.getAroundId().equals(classAround.getId())) {
//
//                }
//            }
//        }
//
//        // 在循环结束后进行判断
//        if (!foundNonEmptyTeam) {
//            // 如果循环结束后没有找到非空班组，显示错误信息
//            return AjaxResult.error("班组不能为空");
//        }
//
//        srcPlanClasses.setDocumentStatus("1");
//        srcPlanClassesService.updateById(srcPlanClasses);
//        return success("修改成功");
//    }


    /**
     * 获取质检详细信息
     */

    @RequestMapping("getPlan")
    public AjaxResult getInfo(Integer planId)
    {
        return success(srcPlanClassesService.getById(planId));
    }

    /**
     * 新增班组
     */

    @PostMapping
    public AjaxResult add(@RequestBody PlanClasses srcPlanClasses)
    {
        srcPlanClasses.setCreateBy(SecurityUtils.getUsername());
        srcPlanClasses.setCreateTime(new Date());
        srcPlanClasses.setDocumentStatus("0");
        boolean b=srcPlanClassesService.save(srcPlanClasses);
        return b?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 修改班组
     */
    @PutMapping
    public AjaxResult edit(@RequestBody PlanClasses srcPlanClasses)
    {
        srcPlanClasses.setUpdateBy(SecurityUtils.getUsername());
        srcPlanClasses.setUpdateTime(new Date());
        srcPlanClasses.setDocumentStatus("1");
        return toAjax(srcPlanClassesService.updateById(srcPlanClasses));
    }

    /**
     * 删除零售
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        srcPlanClassesService.deleteBatchByIds(Arrays.asList(ids));
        return success();
    }

    @RequestMapping("MarketList")
    public AjaxResult MarketList(String id,Integer aroundId) throws ParseException {

        List<TeamsGroups> list=teamsGroupsService.lists(id,aroundId);

        return success(list);
    }
}
